package com.example.g32.park

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.base.entity.ParkEntity
import com.example.base.entity.ParkEntityItem
import com.example.base.entity.Res
import com.example.base.http.ApiServer
import com.example.base.mvi.RequestType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext

class ParkDataSource(val apiServer: ApiServer, val para:String, val reqType: String):PagingSource<Int, ParkEntityItem>() {
    override fun getRefreshKey(state: PagingState<Int, ParkEntityItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ParkEntityItem> {
        return withContext(Dispatchers.IO){
            try {
                val page=params.key?:1
                val list = mutableListOf<ParkEntityItem>()
                var res:Res<ParkEntity>?=null
                var res2:Res<ParkEntityItem>?=null
                if(reqType=="类型"){
                    res = apiServer.getParkByType(para).first()
                    list.addAll(res.data)
                }else if(reqType=="区域"){
                    res = apiServer.getParkByArea(para.toInt()).first()
                    list.addAll(res.data)
                }else if(reqType=="状态"){
                    res = apiServer.getParkByStatus(para).first()
                    list.addAll(res.data)
                }else if(reqType=="车牌号"){
                    res2 = apiServer.getParkByCarNo(para).first()
                    list.add(res2.data)
                }else if (reqType == "Id查找"){
                    res2 = apiServer.queryById(para.toInt()).first()
                    list.add(res2.data)
                }

                if (res?.code==200 || res2?.code==200){
                    LoadResult.Page(list,null,null)
                }else{
                    LoadResult.Error(Exception(res?.message?:res2?.message))
                }
            }catch (e:Exception){
                LoadResult.Error(e)
            }
        }
    }
}